const $ = layui.jquery;
let table = layui.table;
let laydate = layui.laydate;
let form = layui.form;
const dropdown=layui.dropdown;
const tree = layui.tree;
$(() => {
    //渲染表格
    table.render({
        elem: '#tbl',
        url: ctx + "/sys/api/v1/goods",//向后台提交数据的地址
        method: "get",//默认就是get
        toolbar: "#toolbar",
        defaultToolbar: ['filter', 'exports', 'print'],//右边的按钮
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', width: 80, title: 'ID', sort: true, fixed: 'left'},
            {field: 'skuNo', width: 160,title: 'sku编号',fixed: 'left'},
            {
                field: 'pic', width: 120, title: '商品主图', templet: function (row) {
                    if (row.pic) {
                        let url = ctx + "/assets/" + row.pic;
                        return "<div class='pic' style='background-image:url(" + url + ")'><div class='cover'></div></div>";
                    } else {
                        return "";
                    }
                }
            },
            {
                field: 'pic1', width: 120, title: '商品副图', templet: function (row) {
                    if (row.pic1) {
                        let url = ctx + "/assets/" + row.pic1;
                        return "<div class='pic1' style='background-image:url(" + url + ")'><div class='cover'></div></div>";
                    } else {
                        return "";
                    }
                }
            },
            {field: 'name', width: 160, title: '商品名称', sort: true},
            {field: 'alias', width: 160, title: '别名'},
            {field: 'summary', width: 160, title: '摘要'},
            {
                field: 'category', width: 240, title: '所属类别', templet: function (row) {
                    if (row.category) {
                        return row.category.name+"∈"+row.category.parentChain;
                    } else {
                        return "";
                    }
                }
            },
            {
                field: 'brand', width: 160, title: '所属品牌', templet: function (row) {
                    if (row.brand) {
                        return row.brand.name;
                    } else {
                        return "";
                    }
                }
            },
            {field: 'markPrice', width: 160, title: '标价'},
            {field: 'price', width: 160, title: '售价'},
            {field: 'qty', width: 160, title: '库存'},
            {field: 'description', width: 400, title: '简介'},
            {fixed: 'right', title: '操作', width: 200, templet: '#rowbar'}
        ]],
        page: true, // 是否显示分页
        limits: [5, 10, 20, 50],
        limit: 5 // 每页默认显示的数量
    });
    //查询条件，下拉类别树
    fillCategory();

    //查询条件，所属品牌
    fillBrand();

    //添加事件，使用on,工具栏事件
    table.on("toolbar(tbl)", function (obj) {
            if (obj.event === "reset") {
                //重置
                $("#search-form")[0].reset();
                $("[name=categoryId]").val("");//不知为何，使用reset无法清空此隐藏域
            } else if (obj.event === "search") {
                reload();
                $("#search-form")[0].reset();
                $("[name=categoryId]").val("");//不知为何，使用reset无法清空此隐藏域
            } else if (obj.event === "del") {//批量删除，安全删除
                let status = table.checkStatus("tbl");
                let checked = status.data;//获取选中的数据
                let ids = [];
                checked.forEach(it => ids.push(it.id));
                if (ids.length === 0) {
                    layer.msg("请选中您要删除的行")
                } else {
                    layer.confirm("是否确认删除选中的行?", function (index) {
                        deleteByIds(ids);
                        reload();
                        layer.close(index);
                    });
                }
            } else if (obj.event === "add") {
                add();
            } else if (obj.event === "edit") {
                let status = table.checkStatus("tbl");
                let checked = status.data;//获取选中的数据
                if (checked.length === 0) {
                    layer.msg("请选中您要修改的行")
                } else if (checked.length > 1) {
                    layer.msg("一次最多修改一行")
                } else {
                    let goods = checked[0];
                    edit(goods);
                }

            }
        }
    );

//     行工具栏
    table.on("tool(tbl)", function (obj) {

        if (obj.event === "del") {
            let rowData = obj.data;//选中的行的数据
            layer.confirm("是否确认删除选中的行?", function (index) {
                deleteByIds([rowData.id]);
                reload();
                layer.close(index);
            });
        } else if (obj.event === "edit") {
            let goods = obj.data;//选中的行的数据
            edit(goods);
        }else if(obj.event==="view"){
            let goods = obj.data;//选中的行的数据
            show(goods);
        }

    })

})

// 刷新
function reload() {
    //获取表单数据
    let formData = form.val("search-form");

    //重新加载表格，重新获取数据,where里是传给后台的数据
    table.reload('tbl', {
        where: formData
    });
}
//填充品牌下拉列表框
function fillBrand() {
    const url = ctx + "/sys/api/v1/brand/all";
    $.ajax({
        url,
        method: "get",
        dataType: "json",
        success(resp) {
            if (resp.success) {
                let rows = resp.data;
                let $brand = $("[name=brandId]");
                $brand.append("<option value=''>不限</option>");
                for (let row of rows) {
                    $brand.append("<option value='" + row.id + "'>" + row.name + "</option>");
                }
                form.render("select", "search-form");
            }
        }
    });
}

//填充类别
function fillCategory() {
    //查询类别树
    const url = ctx + "/sys/api/v1/category";
    $.ajax({
        url,
        method: "get",
        dataType: "json",
        success(resp) {
            if (resp.success) {
                let treeData = resp.data;

                //实例化下拉框
                dropdown.render({
                    id: "category-dropdown",
                    elem: "[name=categoryName]",
                    content: "<div id='category-tree' style='min-width: 300px;height: 300px;overflow-y: scroll'></div>",
                    //每次展开下拉面板都会触发，由于每次关闭面板后，整个dom会被移除，且不打开面板时，是不会创建dom的
                    //所有tree的渲染必须放在ready函数中
                    ready() {
                        tree.render({
                            elem: "#category-tree",
                            data: treeData,
                            customName: {
                                title: "name"
                            },
                            onlyIconControl: true,//仅能通过点击节点前图标控制收缩和展开
                            click(obj) {
                                let node = obj.data;//节点数据
                                $("[name=categoryName]").val(node.name);
                                $("[name=categoryId]").val(node.id);
                                //关闭下拉面板，参数为下拉实例的id
                                dropdown.close("category-dropdown");
                            }
                        });
                    }
                });
            }
        }
    });
}
// 删除
function deleteByIds(ids) {
    const url = ctx + "/sys/api/v1/goods"
    $.ajax({
        url,
        method: "delete",
        data: {
            ids
        },
        traditional: true,
        success(resp) {//200
            if (resp.success) {
                layer.msg(resp.message || "删除成功，共删除" + resp.data + "条数据")
            } else {
                layer.msg(resp.message || "删除失败")
            }
        }, error(resp) {
            console.log(resp);
        }
    })
}

// 增加
function add() {
    layer.open({
        type: 2,//iframe层
        title: "新增商品",
        area: ['800px', '500px'],
        skin: 'layui-layer-rim', // 加上边框
        content: "/vm/sys/goods/add",
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            let iframeWin = layero.find("iframe")[0].contentWindow;
            iframeWin.doSubmit(function (success) {
                if (success) {
                    layer.msg("添加成功");
                    layer.close(index);//关闭当前窗口
                    reload();
                } else {
                    layer.alert("添加失败", {
                        icon: 2,
                        title: "错误"
                    });
                }
            })
        }
    });
}

// 修改
function edit(goods) {
    layer.open({
        type: 2,//iframe层
        title: "修改商品",
        area: ['800px', '500px'],
        skin: 'layui-layer-rim', // 加上边框
        content: "/vm/sys/goods/edit?id=" + goods.id,
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            let iframeWin = layero.find("iframe")[0].contentWindow;
            iframeWin.doSubmit(function (success) {
                if (success) {
                    layer.msg("修改成功");
                    layer.close(index);//关闭当前窗口
                    reload();
                } else {
                    layer.alert("修改失败", {
                        icon: 2,
                        title: "错误"
                    });
                }
            })
        }
    });
}
//展示
function show(goods) {
    layer.open({
        type: 2,//iframe层
        title: "查看商品",
        area: ['1000px', '600px'],
        skin: 'layui-layer-rim', // 加上边框
        content: "/vm/sys/goods/show?id=" + goods.id,
        btn: ['确定', '取消'],
    });
}